// pages/commit/index.js
import Toast from "@vant/weapp/toast/toast";
const http = require("../../api/http");
const req = require("../../utils/request");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    FacilityTypeList: [], // 设施类型
    FacilityList: [], // 设施详情
    baseUrl: req.base_url,
    active: 0,
    activeStep: 0,

    fileList: [],
    name: "", //名称
    open: false, //选择器状态
    latitude: "", //维度
    longitude: "", //经度
    campLocation: "", //位置
    address: "", //详细地址信息
    timeOpen: false, //控制时间选择的开关
    timeDetailOpen: false, //控制月份选择器
    timeType: 1, //营业时间类型 1全年，2月份
    time: "", //营业时间
    columns: [
      {
        values: [
          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "七月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月",
        ], //月份
        className: "column1",
        defaultIndex: 0,
      },
      {
        values: [
          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "七月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月",
        ], //月份
        className: "column2",
        defaultIndex: 2,
      },
    ],
    campTypes: ["综合营地", "微型营地", "帐篷营地", "教育营地", "运动营地"],
    checkedType: "",
    type: "", //营地类型
    contacts: "", //联系人姓名
    phone: "", //联系电话
    introduce: "", //营地介绍
    campImgs: [], //商家信息图片(运营者)
    tourisCampImgs: [], //游客图片(非运营者)
    facilitiesList: [], //服务设施列表
    selectFacilitiesList: [], //选中的服务设施列表
    campId: "", //商家上传后的营地id
    steps: [
      {
        text: "步骤一",
        desc: "营地信息",
      },
      {
        text: "步骤二",
        desc: "服务设施",
      },
      {
        text: "步骤三",
        desc: "营地介绍",
      },
      {
        text: "步骤四",
        desc: "预览",
      },
    ],

    introduction: "",
    isAcceptingVehicles: false,
    vehicleType: null,
  },

  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },

  // afterRead(event) {
  //   const { file } = event.detail;
  //   this.setData({
  //     campImgs: [...this.data.campImgs, ...file.map((f) => f.path)],
  //   });
  //   console.log("campimgs", this.campImgs);
  //   // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  //   // wx.uploadFile({
  //   //   url: this.baseUrl + "/ruoyi/uploadPath", // 仅为示例，非真实的接口地址
  //   //   filePath: file.url,
  //   //   name: "file",
  //   //   formData: { user: "test" },
  //   //   success(res) {
  //   //     // 上传完成需要更新 fileList
  //   //     const { fileList = [] } = this.data;
  //   //     fileList.push({ ...file, url: res.data });
  //   //     this.setData({ fileList });
  //   //     console.log("filelist: ", fileList);
  //   //   },
  //   // });
  // },

  /** 3 */
  onInputIntroduction(e) {
    this.setData({
      introduction: e.detail.value,
    });
  },
  onSwitchChange(e) {
    this.setData({
      isAcceptingVehicles: e.detail.value,
    });
  },
  onAddTypeClick() {
    // 跳转到添加车辆类型的页面
    wx.navigateTo({
      url: "/pages/addVehicleType/addVehicleType",
    });
  },
  onLoad(query) {
    // 监听子页面传递的数据
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("acceptDataFromOpenedPage", (data) => {
      console.log(data); // 打印接收到的数据
      // 更新页面显示
      this.setData({
        vehicleType: data,
      });
    });
  },

  bindCampTypeChange: function (e) {
    this.setData({
      campTypeIndex: e.detail.value,
    });
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
    });
  },

  bindOpenTimeChange: function (e) {
    this.setData({
      openTimeIndex: e.detail.value,
    });
  },

  chooseImage: function () {
    const that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          images: that.data.images.concat(res.tempFilePaths),
        });
      },
    });
  },
  bindSwitchChange: function (e) {
    this.setData({
      isPublicPhone: e.detail.value,
    });
  },
  formSubmit: function (e) {
    console.log("form发生了submit事件，携带数据为：", e.detail.value);
    // 这里可以添加提交数据到服务器的逻辑
  },
  saveDraft: function () {
    const formData = this.data;
    console.log("保存草稿，当前数据为：", formData);
    // 这里可以添加保存草稿的逻辑
  },
  nextStep() {
    let newActiveStep = this.data.active + 1;
    if (newActiveStep <= 3) {
      this.setData({
        active: newActiveStep,
      });
    } else {
      wx.showToast({
        title: "所有步骤已完成",
        icon: "success",
      });
    }
  },
  prevStep() {
    let newActiveStep = this.data.active - 1;
    if (newActiveStep >= 0) {
      this.setData({
        active: newActiveStep,
      });
    } else {
      wx.showToast({
        title: "已经是第一步",
        icon: "none",
      });
    }
  },
  onOptionTap(e) {
    const index = e.currentTarget.dataset.index;
    const category = e.currentTarget.dataset.category;

    let newData = {};
    switch (category) {
      case "campTypes":
        newData.campTypes = this.data.campTypes.map((item, i) => {
          if (i === index) {
            return { ...item, checked: !item.checked };
          }
          return item;
        });
        break;
      case "serviceFacilities":
        newData.serviceFacilities = this.data.serviceFacilities.map(
          (item, i) => {
            if (i === index) {
              return { ...item, checked: !item.checked };
            }
            return item;
          }
        );
        break;
      case "accommodations":
        newData.accommodations = this.data.accommodations.map((item, i) => {
          if (i === index) {
            return { ...item, checked: !item.checked };
          }
          return item;
        });
        break;
      case "campingConditions":
        newData.campingConditions = this.data.campingConditions.map(
          (item, i) => {
            if (i === index) {
              return { ...item, checked: !item.checked };
            }
            return item;
          }
        );
        break;
      case "campEnvironments":
        newData.campEnvironments = this.data.campEnvironments.map((item, i) => {
          if (i === index) {
            return { ...item, checked: !item.checked };
          }
          return item;
        });
        break;
    }

    this.setData(newData);
  },

  onChangeCampType(e) {
    const values = e.detail.value;
    this.setData({
      campTypes: this.data.campTypes.map((item) => ({
        ...item,
        checked: values.includes(item.value),
      })),
    });
  },

  onChangeServiceFacilities(e) {
    const values = e.detail.value;
    this.setData({
      serviceFacilities: this.data.serviceFacilities.map((item) => ({
        ...item,
        checked: values.includes(item.value),
      })),
    });
  },

  onChangeAccommodation(e) {
    const values = e.detail.value;
    this.setData({
      accommodations: this.data.accommodations.map((item) => ({
        ...item,
        checked: values.includes(item.value),
      })),
    });
  },

  onChangeCampingConditions(e) {
    const values = e.detail.value;
    this.setData({
      campingConditions: this.data.campingConditions.map((item) => ({
        ...item,
        checked: values.includes(item.value),
      })),
    });
  },

  onChangeCampEnvironment(e) {
    const values = e.detail.value;
    this.setData({
      campEnvironments: this.data.campEnvironments.map((item) => ({
        ...item,
        checked: values.includes(item.value),
      })),
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    // 监听子页面传递的数据
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("acceptDataFromOpenedPage", (data) => {
      console.log(data); // 打印接收到的数据
      // 更新页面显示
      this.setData({
        vehicleType: data,
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getFacilityTypeAndDetails();
    // var query = {};
    // 调用接口获取设施类型
    // http.getFacilityType(query).then((res) => {
    //   // console.log(res);
    //   if (res.code === 200) {
    //     console.log(res, "getFacilityType");
    //     //解构出data 赋值给
    //     const { data } = res;
    //     // 设置数据
    //     this.setData({
    //       FacilityTypeList: data,
    //     });
    //     // 调用接口获取设施详情
    //     var query = {};
    //     http.getFacility(query).then((res) => {
    //       // console.log(res);
    //       if (res.code === 200) {
    //         console.log(res, "getFacility");
    //         //解构出data 赋值给
    //         const { data } = res;
    //         // 设置数据
    //         this.setData({
    //           FacilityList: data,
    //         });
    //       } else {
    //         // 失败
    //         wx.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       }
    //     });
    //   } else {
    //     // 失败
    //     wx.showToast({
    //       title: res.msg,
    //       icon: "none",
    //     });
    //   }
    // });
  },
  getFacilityTypeAndDetails: function () {
    var query = {};
    http
      .getFacilityType(query)
      .then((res) => {
        if (res.code === 200) {
          console.log(res, "getFacilityType");
          const { data } = res;

          // 设置 FacilityTypeList
          this.setData({
            FacilityTypeList: data,
          });
          // 使用 ftIds 作为查询参数调用 getFacility 接口
          this.getFacility();
        } else {
          // 失败
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      })
      .catch((error) => {
        console.error(error);
        wx.showToast({
          title: "请求失败",
          icon: "none",
        });
      });
  },

  getFacility: function () {
    var query = {};
    http
      .getFacility(query)
      .then((res) => {
        if (res.code === 200) {
          console.log(res, "getFacility");
          const { data } = res;

          // 设置 FacilityList
          this.setData({
            FacilityList: data,
          });
        } else {
          // 失败
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      })
      .catch((error) => {
        console.error(error);
        wx.showToast({
          title: "请求失败",
          icon: "none",
        });
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},

  /********************************************************** */

  // 营地名称
  changeName(e) {
    this.setData({
      name: e.detail.value,
    });
  },
  // 营地位置
  selectSite() {
    // 检查用户权限状态
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting["scope.userLocation"]) {
          // 用户尚未授权或已拒绝授权
          // 主动请求授权
          this.requestLocationAuthorization();
        } else {
          // 已经授权，直接获取位置信息
          this.getUserLocation();
        }
      },
    });
  },
  // 请求授权
  requestLocationAuthorization() {
    // 请求用户授权精确位置
    wx.authorize({
      scope: "scope.userLocation",
      success: () => {
        this.getUserLocation();
      },
      fail: (err) => {
        // 拒绝授权，提示用户收到开启
        this.showSettingPrompt();
      },
    });
  },
  // 提示用户开启授权
  showSettingPrompt() {
    wx.showModal({
      title: "需要位置权限",
      content: "请在设置中开启位置权限以正常使用本功能。",
      showCancel: false,
      confirmText: "去设置",
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting["scope.userLocation"]) {
                // 用户在设置中开启了位置权限
                this.getUserLocation();
              } else {
                // 用户仍然拒绝位置权限
                console.log("用户仍未开启位置权限");
              }
            },
          });
        }
      },
    });
  },
  //获取位置信息
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: "gcj02",
      success: (res) => {
        console.log(res, "返回的数据");
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.chooseLocation({
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          success: (res) => {
            console.log(res, "########");
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              campLocation: res.address,
            });
          },
          fail: (err) => {
            console.log(err);
          },
        });
      },
      fail: (err) => {
        console.error("获取位置失败:", err);
      },
      complete: () => {
        console.log("位置获取操作已完成");
      },
    });
  },
  // 具体位置
  changeAddress(e) {
    this.setData({
      address: e.detail.value,
    });
  },
  //营业时间
  selectTime() {
    this.setData({
      open: false,
      timeOpen: true,
      time: "全年",
    });
  },
  onChange(e) {
    this.setData({
      timeType: e.detail,
    });
    if (e.detail == 1) {
      this.setData({
        timeDetailOpen: false,
        time: "全年",
      });
    } else {
      this.setData({
        timeDetailOpen: true,
      });
    }
  },
  onTimeChange(e) {
    console.log(e);
    this.setData({
      time: e.detail.value.join("-"),
    });
  },
  // 关闭时间
  closeTime() {
    this.setData({
      timeOpen: false,
    });
  },
  // 确定时间
  sureTime() {
    this.setData({
      timeOpen: false,
    });
    console.log(this.data.time);
  },
  // 选择营地类型
  selectType() {
    this.setData({
      timeOpen: false,
      open: true,
    });
  },
  bindChange(e) {
    let val = e.detail.value[0];
    this.setData({
      checkedType: this.data.campTypes[val],
    });
  },
  closeSelect() {
    this.setData({
      open: false,
    });
  },
  sureSelect() {
    this.setData({
      type: this.data.checkedType || "综合营地",
      open: false,
    });
  },
  // 绑定联系人
  changeContacts(e) {
    this.setData({
      contacts: e.detail.value,
    });
    console.log(123);
  },
  // 绑定联系电话
  changePhone(e) {
    this.setData({
      phone: e.detail.value,
    });
  },
  // 绑定营地介绍
  changeIntroduce(e) {
    this.setData({
      introduce: e.detail.value,
    });
  },

  // afterRead(event) {
  //   console.log(event);
  // },
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: "https://example.weixin.qq.com/upload", // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      formData: { user: "test" },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = this.data;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
      },
    });
  },
  //删除图片
  delImgs(u) {
    this.data.campImgs.splice(u.currentTarget.dataset.index, 1);
    this.setData({
      campImgs: this.data.campImgs,
    });
  },
  // 上一步
  prev() {
    this.setData({
      active: 0,
    });
  },
  // 下一步
  next() {
    // let flag = this.checkCamp();
    let flag = true;
    if (flag) {
      this.setData({
        active: 1,
      });
    }
  },
  // 商家提交数据
  async businessSub() {
    await this.subCamp();
    await this.subService();
  },
  // 返回营地类型id
  campType(value) {
    return this.data.campTypes.indexOf(value) + 1;
  },
  // 提交营地信息
  async subCamp() {
    let userInfo = wx.getStorageSync("userInfo");
    let campType = this.campType(this.data.type);
    let res = await http.addCamp({
      userId: userInfo.userId,
      userType: 1,
      campType,
      campName: this.data.name,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude,
      location: this.data.campLocation,
      address: this.data.address,
      timeType: this.data.timeType,
      specificTime: this.data.time,
      linkman: this.data.contacts,
      phone: this.data.phone,
      imageUrl: this.data.campImgs.join(","),
      introduce: this.data.introduce,
      campUser: {
        userId: userInfo.userId,
      },
    });
    this.setData({
      campId: res.msg,
    });
  },
  // 上传服务设施
  async subService() {
    let res = await http.addService({
      campId: this.data.campId,
      facilityIds: this.data.selectFacilitiesList,
    });
    console.log(res);
    if (res.code == 200) {
      wx.redirectTo({
        url: `../detail/detail?campId=${this.data.campId}`,
      });
    }
  },
  // 选中服务设施
  selectIcon(e) {
    let a, b, select, list, id, data;
    list = this.data.facilitiesList;
    id = e.currentTarget.dataset.id;
    data = this.data.selectFacilitiesList;
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i;
          b = j;
        }
      }
    }
    select = list[a].facilities[b].state;
    // 如果没有选中，则选中
    if (select == 1) {
      list[a].facilities[b].state = 2;
      data.push(id);
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      });
    } else {
      // 已经选中，则取消选中
      list[a].facilities[b].state = 1;
      let index = data.indexOf(id);
      data.splice(index, 1);
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      });
    }

    console.log(this.data.selectFacilitiesList);
  },
});
